<template>
  <div class="pose-detection-container">
    <div class="page-header">
      <h1 class="page-title">人体关键点检测</h1>
      <p class="page-description">上传视频文件，使用AI算法检测人体关键点并展示结果</p>
      
      <!-- 示例图片展示区域 -->
      <div class="example-section">
        <div class="example-image-container">
          <img 
            src="/示例.jpeg" 
            alt="示例图片" 
            class="example-image"
            @error="onExampleImageError"
            @load="onExampleImageLoad"
          />
          <div class="example-overlay">
            <p class="example-text">点击查看示例</p>
          </div>
        </div>
      </div>
    </div>

    <div class="main-content">
      <!-- 文件上传区域 -->
      <div class="upload-section">
        <div class="upload-card">
          <div class="upload-area" 
               :class="{ 'drag-over': isDragOver, 'has-file': selectedFile }"
               @dragover.prevent="handleDragOver"
               @dragleave.prevent="handleDragLeave"
               @drop.prevent="handleDrop"
               @click="triggerFileInput">
            <div v-if="!selectedFile" class="upload-placeholder">
              <icon-upload class="upload-icon" />
              <p class="upload-text">点击或拖拽视频文件到此处上传</p>
              <p class="upload-hint">支持 MP4, AVI, MOV 格式</p>
            </div>
            <div v-else class="file-info">
              <icon-video-camera class="file-icon" />
              <div class="file-details">
                <p class="file-name">{{ selectedFile.name }}</p>
                <p class="file-size">{{ formatFileSize(selectedFile.size) }}</p>
              </div>
              <button class="remove-btn" @click.stop="removeFile">
                <icon-close />
              </button>
            </div>
          </div>
          <input 
            ref="fileInput"
            type="file" 
            accept="video/*"
            @change="handleFileSelect"
            style="display: none"
          />
        </div>
      </div>

      <!-- 控制按钮 -->
      <div class="control-section">
        <div class="control-options">
          <a-radio-group v-model="processingMode" :disabled="isProcessing">
            <a-radio value="realtime">实时检测</a-radio>
          </a-radio-group>
        </div>
        
        <div class="control-buttons">
          <a-button 
            v-if="processingMode === 'realtime' && !isRealtimeProcessing"
            type="primary" 
            size="large"
            :disabled="!selectedFile"
            @click="startRealtimeDetection"
            class="detect-btn">
            <icon-play-circle />
            开始实时检测
          </a-button>
          
          <a-button 
            v-if="processingMode === 'realtime' && isRealtimeProcessing"
            type="danger" 
            size="large"
            @click="stopRealtimeDetection"
            class="stop-btn">
            <icon-pause />
            停止检测
          </a-button>
          
          
          <a-button 
            size="large"
            :disabled="!selectedFile || isProcessing || isRealtimeProcessing"
            @click="resetDetection"
            class="reset-btn">
            <icon-refresh />
            重置
          </a-button>
        </div>
      </div>

      <!-- 结果显示区域 -->
      <div v-if="detectionResult || isProcessing || isRealtimeProcessing" class="result-section">
        <div class="result-header">
          <h3>检测结果</h3>
          <div class="result-stats" v-if="detectionResult">
            <span class="stat-item">
              <icon-user /> 检测到 {{ detectionResult.personCount || 0 }} 个人
            </span>
            <span class="stat-item">
              <icon-clock-circle /> 处理时间: {{ detectionResult.processingTime || 0 }}s
            </span>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="isProcessing" class="loading-container">
          <a-spin size="large">
            <div class="loading-content">
              <icon-loading />
              <p>正在处理视频，请稍候...</p>
            </div>
          </a-spin>
        </div>

        <!-- 结果展示 -->
        <div v-else-if="detectionResult || isRealtimeProcessing" class="result-content">
          <!-- 实时检测模式 -->
          <div v-if="processingMode === 'realtime'" class="realtime-container">
            <div class="realtime-header">
              <h4>实时人体关键点检测</h4>
              <div class="realtime-stats">
                <span class="stat-item">
                  <icon-user /> 检测到 {{ currentFrameData?.detections?.length || 0 }} 人
                </span>
                <span class="stat-item">
                  <icon-clock-circle /> 帧 {{ currentFrameData?.frame || 0 }} / {{ currentFrameData?.total_frames || 0 }}
                </span>
                <span class="stat-item">
                  <icon-video-camera /> {{ currentFrameData?.video_info?.fps || 0 }} FPS
                </span>
              </div>
            </div>
            
            <div class="realtime-display">
              <img 
                v-if="currentFrameData?.image"
                :src="`data:image/jpeg;base64,${currentFrameData.image}`"
                class="realtime-image"
                @load="onRealtimeImageLoaded">
              <div v-else class="no-result">
                <p>等待视频数据...</p>
              </div>
            </div>
            
            <div class="realtime-controls">
              <a-button 
                v-if="!isRealtimeProcessing"
                type="primary"
                @click="startRealtimeDetection"
                :disabled="!selectedFile">
                <icon-play-circle />
                开始检测
              </a-button>
              <a-button 
                v-else
                type="danger"
                @click="stopRealtimeDetection">
                <icon-pause />
                停止检测
              </a-button>
            </div>
          </div>


          <!-- 关键点数据表格 -->
          <div class="keypoints-table">
            <h4>关键点数据</h4>
            <a-table 
              :columns="keypointColumns"
              :data="keypointData"
              :pagination="false"
              :scroll="{ y: 300 }"
              size="small">
            </a-table>
          </div>

          <!-- 下载按钮 -->
          <div class="download-section">
            <a-button @click="downloadKeypoints">
              <icon-file />
              下载关键点数据
            </a-button>
          </div>
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        <a-alert 
          :message="errorMessage"
          type="error"
          show-icon
          closable
          @close="errorMessage = ''">
        </a-alert>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import {
  IconUpload,
  IconVideoCamera,
  IconClose,
  IconPlayCircle,
  IconRefresh,
  IconUser,
  IconClockCircle,
  IconLoading,
  IconDownload,
  IconFile,
  IconPause
} from '@arco-design/web-vue/es/icon'
import { poseDetectionAPI } from '@/utils/api'

// 响应式数据
const selectedFile = ref(null)
const isDragOver = ref(false)
const isProcessing = ref(false)
const detectionResult = ref(null)
const errorMessage = ref('')
const fileInput = ref(null)
const processingMode = ref('realtime') // 只保留实时检测
const isRealtimeProcessing = ref(false)
const currentFrameData = ref(null)
const realtimeStream = ref(null)

// 关键点数据表格列定义
const keypointColumns = [
  {
    title: '帧数',
    dataIndex: 'frame',
    key: 'frame',
    width: 80
  },
  {
    title: '人员ID',
    dataIndex: 'personId',
    key: 'personId',
    width: 80
  },
  {
    title: '关键点数量',
    dataIndex: 'keypointCount',
    key: 'keypointCount',
    width: 100
  },
  {
    title: '置信度',
    dataIndex: 'confidence',
    key: 'confidence',
    width: 100
  },
  {
    title: '边界框',
    dataIndex: 'bbox',
    key: 'bbox',
    width: 150
  }
]

// 关键点数据
const keypointData = ref([])

// 文件大小格式化
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 拖拽处理
const handleDragOver = (e) => {
  e.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = (e) => {
  e.preventDefault()
  isDragOver.value = false
}

const handleDrop = (e) => {
  e.preventDefault()
  isDragOver.value = false
  
  const files = e.dataTransfer.files
  if (files.length > 0) {
    handleFile(files[0])
  }
}

// 文件选择处理
const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileSelect = (e) => {
  const file = e.target.files[0]
  if (file) {
    handleFile(file)
  }
}

const handleFile = (file) => {
  // 检查文件类型 - 只允许视频文件
  if (!file.type.startsWith('video/')) {
    Message.error('请选择视频文件')
    return
  }

  // 检查文件大小 (限制为100MB)
  const maxSize = 100 * 1024 * 1024
  if (file.size > maxSize) {
    Message.error('文件大小不能超过100MB')
    return
  }

  selectedFile.value = file
  
  // 重置之前的结果
  detectionResult.value = null
  keypointData.value = []
  errorMessage.value = ''
}

// 移除文件
const removeFile = () => {
  selectedFile.value = null
  detectionResult.value = null
  keypointData.value = []
  errorMessage.value = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}


// 重置检测
const resetDetection = () => {
  // 停止实时处理
  if (isRealtimeProcessing.value) {
    stopRealtimeDetection()
  }
  removeFile()
  Message.info('已重置')
}

// 开始实时检测
const startRealtimeDetection = async () => {
  if (!selectedFile.value) {
    Message.error('请先选择视频文件')
    return
  }

  try {
    // 开始实时处理
    const response = await poseDetectionAPI.startRealtimeProcessing(selectedFile.value)
    
    if (response.success) {
      isRealtimeProcessing.value = true
      Message.success('开始实时检测')
      
      // 等待一下让后端开始处理
      setTimeout(() => {
        // 创建实时流连接
        realtimeStream.value = poseDetectionAPI.createRealtimeStream(
          (data) => {
            // 接收实时数据
            console.log('收到实时数据:', data)
            currentFrameData.value = data
            
            // 处理关键点数据
            if (data.detections && data.detections.length > 0) {
              const processedKeypoints = []
              data.detections.forEach((detection, index) => {
                processedKeypoints.push({
                  frame: data.frame || 0,
                  personId: detection.track_id || index,
                  keypointCount: detection.keypoints ? detection.keypoints.length : 0,
                  confidence: detection.confidence || 0,
                  bbox: detection.bbox ? `[${detection.bbox.join(', ')}]` : 'N/A'
                })
              })
              keypointData.value = processedKeypoints
            } else {
              keypointData.value = []
            }
          },
          (error) => {
            // 处理错误
            console.error('实时流错误:', error)
            stopRealtimeDetection()
          },
          () => {
            // 连接完成
            console.log('实时流连接完成')
            stopRealtimeDetection()
          }
        )
      }, 1000)  // 等待1秒
    } else {
      console.log('启动实时检测响应:', response)
    }
  } catch (error) {
    console.error('启动实时检测失败:', error)
    // 不显示错误消息，静默处理
  }
}

// 停止实时检测
const stopRealtimeDetection = async () => {
  try {
    // 关闭实时流
    if (realtimeStream.value) {
      realtimeStream.value()
      realtimeStream.value = null
    }
    
    // 停止后端处理
    await poseDetectionAPI.stopRealtimeProcessing()
    
    isRealtimeProcessing.value = false
    currentFrameData.value = null
    Message.info('已停止实时检测')
  } catch (error) {
    console.error('停止实时检测失败:', error)
    // 不显示错误消息，静默处理
  }
}

// 媒体加载完成
const onRealtimeImageLoaded = () => {
  console.log('实时图像加载完成')
}

// 示例图片加载处理
const onExampleImageLoad = () => {
  console.log('示例图片加载完成')
}

const onExampleImageError = () => {
  console.error('示例图片加载失败')
}


// 下载关键点数据
const downloadKeypoints = () => {
  if (keypointData.value.length === 0) {
    Message.warning('没有关键点数据可下载')
    return
  }

  const csvContent = [
    '帧数,人员ID,关键点数量,置信度,边界框',
    ...keypointData.value.map(row => 
      `${row.frame},${row.personId},${row.keypointCount},${row.confidence},"${row.bbox}"`
    )
  ].join('\n')

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `keypoints_data_${Date.now()}.csv`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<style scoped>
.pose-detection-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 10px;
}

.page-description {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

/* 示例图片区域样式 */
.example-section {
  margin-top: 20px;
  text-align: center;
}


.example-image-container {
  position: relative;
  display: inline-block;
  max-width: 600px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  cursor: pointer;
}

.example-image-container:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
}

.example-image {
  width: 100%;
  height: auto;
  display: block;
  transition: all 0.3s ease;
}

.example-image-container:hover .example-image {
  transform: scale(1.05);
}

.example-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, rgba(79, 172, 254, 0.8) 0%, rgba(0, 242, 254, 0.8) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s ease;
}

.example-image-container:hover .example-overlay {
  opacity: 1;
}

.example-text {
  color: white;
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
}

.upload-section {
  margin-bottom: 30px;
}

.upload-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 2px dashed #e1e8ed;
  transition: all 0.3s ease;
}

.upload-card:hover {
  border-color: #4facfe;
  box-shadow: 0 12px 40px rgba(79, 172, 254, 0.15);
}

.upload-area {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 12px;
}

.upload-area.drag-over {
  background: linear-gradient(45deg, rgba(79, 172, 254, 0.1) 0%, rgba(0, 242, 254, 0.1) 100%);
  border-color: #4facfe;
}

.upload-area.has-file {
  min-height: 120px;
  background: #f8f9fa;
}

.upload-placeholder {
  text-align: center;
  color: #7f8c8d;
}

.upload-icon {
  font-size: 48px;
  color: #4facfe;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 18px;
  font-weight: 500;
  margin: 0 0 8px 0;
}

.upload-hint {
  font-size: 14px;
  margin: 0;
  opacity: 0.7;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 16px;
  width: 100%;
  padding: 16px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e1e8ed;
}

.file-icon {
  font-size: 32px;
  color: #4facfe;
}

.file-details {
  flex: 1;
}

.file-name {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
  margin: 0 0 4px 0;
}

.file-size {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.remove-btn {
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.remove-btn:hover {
  background: #ff3742;
  transform: scale(1.1);
}

.control-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
}

.control-options {
  display: flex;
  gap: 20px;
  align-items: center;
}

.control-buttons {
  display: flex;
  gap: 16px;
}

.detect-btn {
  background: linear-gradient(45deg, #4facfe 0%, #00f2fe 100%);
  border: none;
  height: 48px;
  padding: 0 32px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 24px;
  box-shadow: 0 4px 16px rgba(79, 172, 254, 0.3);
  transition: all 0.3s ease;
}

.detect-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(79, 172, 254, 0.4);
}

.reset-btn {
  height: 48px;
  padding: 0 24px;
  border-radius: 24px;
  border: 2px solid #e1e8ed;
  color: #7f8c8d;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  border-color: #4facfe;
  color: #4facfe;
}

.result-section {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f1f3f4;
}

.result-header h3 {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.result-stats {
  display: flex;
  gap: 24px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #7f8c8d;
}

.loading-container {
  text-align: center;
  padding: 60px 20px;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.loading-content p {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.media-container {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.media-container h4 {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 16px 0;
}

.result-media {
  width: 100%;
  max-width: 800px;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.no-result {
  text-align: center;
  padding: 40px;
  color: #7f8c8d;
  font-style: italic;
}

/* 实时检测样式 */
.realtime-container {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
}

.realtime-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 2px solid #e1e8ed;
}

.realtime-header h4 {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.realtime-stats {
  display: flex;
  gap: 20px;
}

.realtime-stats .stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #7f8c8d;
  background: white;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #e1e8ed;
}

.realtime-display {
  text-align: center;
  margin-bottom: 20px;
}

.realtime-image {
  max-width: 100%;
  max-height: 500px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border: 2px solid #e1e8ed;
}

.realtime-controls {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.stop-btn {
  background: linear-gradient(45deg, #ff4757 0%, #ff3742 100%);
  border: none;
  height: 48px;
  padding: 0 32px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 24px;
  box-shadow: 0 4px 16px rgba(255, 71, 87, 0.3);
  transition: all 0.3s ease;
}

.stop-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(255, 71, 87, 0.4);
}

.keypoints-table {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.keypoints-table h4 {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 16px 0;
}

.download-section {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 20px;
  border-top: 2px solid #f1f3f4;
}

.error-message {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pose-detection-container {
    padding: 10px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .example-image-container {
    max-width: 450px;
  }
  
  .control-section {
    flex-direction: column;
    align-items: center;
  }
  
  .result-stats {
    flex-direction: column;
    gap: 8px;
  }
  
  .download-section {
    flex-direction: column;
    align-items: center;
  }
}
</style>
